package com.iwhalecloud.bss.kite.cucc.service.goods;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.goods.ILocalAddtionOfferService;
import com.iwhalecloud.bss.kite.cucc.client.dto.goods.WholeQuickEntryDTO;
import com.iwhalecloud.bss.kite.cucc.service.cache.LocalWholeQuickEntryCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.ztesoft.bss.svcability.util.DecimalCalc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @author lyx
 * @date 2020年9月15日
 * @version V1.0
 * @Package com.iwhalecloud.bss.kite.cucc.service.goods
 */
@Service
public class LocalAddtionOfferService implements ILocalAddtionOfferService {

    @Autowired
    IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Override
    public void changeWholeQuickEntryPrice(String sceneInstId, List<String> offerInstIdList, String custId,
        String wholePrice) {
        if (KiteStringUtils.isEmpty(wholePrice)) {
            wholePrice = "0.00";
        }
        double wholePriceD = Double.parseDouble(wholePrice);
        double offerPrice = DecimalCalc.div(wholePriceD, offerInstIdList.size()); // 保留两位小数
       // BigDecimal bg = new BigDecimal(offerPrice);
        BigDecimal bg = BigDecimal.valueOf(offerPrice);
        offerPrice = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String offerPriceStr = String.valueOf(offerPrice);
        offerInstIdList.stream().forEach(t -> {
            KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, t);
            if (Objects.nonNull(offerInst)) {
                operateSceneInstService.setAttrValue(sceneInstId, offerInst.getInstType(), offerInst.getInstId(),
                    "200002023", offerPriceStr, offerPriceStr);
            }
        });
    }

    @Override
    public boolean checkExpAndEffDate(String sceneInstId, String custId) {
        // 所有的主套餐
        List<KiteOfferInst> mianOfferInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
        // 已实例化的可选包
        List<KiteOfferInst> additionalOfferInsts = new ArrayList<>();
        for (KiteOfferInst kiteOfferInst : mianOfferInsts) {
            additionalOfferInsts.addAll(
                querySceneInstService.listAdditionalOfferInstsFromOfferInst(custId, kiteOfferInst.getOfferInstId()));
        }
        additionalOfferInsts = additionalOfferInsts.stream().filter(t -> ActionType.A.equals(t.getActionType())).collect(Collectors.toList());
        Map<String, List<KiteOfferInst>> additionalOfferMap = KiteListUtils.groupBy(additionalOfferInsts, "specId");
        for (Map.Entry<String, List<KiteOfferInst>> entry : additionalOfferMap.entrySet()) {
            List<KiteOfferInst> additionalOfferInstList = entry.getValue();
            if (additionalOfferInstList.size() <= 1) {
                continue;
            }
            for (int i = 1; i < additionalOfferInstList.size(); i++) {
                // 上一个资费产品的失效时间
                String expDate = additionalOfferInstList.get(i - 1).getAttr("200000173").getValue();
                // 当前资费产品的生效时间
                String effDate = additionalOfferInstList.get(i).getAttr("200000172").getValue();
                if (KiteStringUtils.isEmpty(expDate) || KiteStringUtils.isEmpty(effDate)) {
                    return true;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date exp = sdf.parse(expDate);
                    Date eff = sdf.parse(effDate);
                    long expDateLong = exp.getTime();
                    long effDateLong = eff.getTime();
                    long second = (effDateLong - expDateLong) / (1000);
                    if (second > 1) {
                        return false;
                    }
                }
                catch (ParseException e) {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut(e.getStackTrace());
                }
            }
        }
        return true;
    }

    @Override
    public List<KiteOfferInst> updateWholeQuickEntryAttr(String sceneInstId, List<String> offerInstIdList,
        String custId, String filedName, String filedValue, String wholeQuickEntryId) {

        if (KiteStringUtils.equals(filedName, "whole_price") && KiteListUtils.isNotEmpty(offerInstIdList)) {
            this.changeWholeQuickEntryPrice(sceneInstId, offerInstIdList, custId, filedValue);
        }

        // 修改全程协议快捷录入缓存
//        WholeQuickEntryDTO wholeQuickEntryDTO = LocalWholeQuickEntryCache.get(wholeQuickEntryId);
//        Map<String, Object> attrMap = wholeQuickEntryDTO.getWholeQuickEntryAttr();
//        if (KiteMapUtils.isEmpty(attrMap)) {
//            attrMap = new HashMap<>();
//        }
//        attrMap.put(filedName, filedValue);
//        wholeQuickEntryDTO.setWholeQuickEntryAttr(attrMap);
//        LocalWholeQuickEntryCache.put(wholeQuickEntryId, wholeQuickEntryDTO);

//        Map<String, WholeQuickEntryVO> wholeQuickEntryMap = querySceneInstService.getExtParameterValue(sceneInstId, "wholeQuickEntryMap");
//        WholeQuickEntryVO wholeQuickEntryVO = wholeQuickEntryMap.get(wholeQuickEntryId);
//        wholeQuickEntryVO.getWholeQuickEntryAttrList().forEach(kiteAttr -> {
//            if (KiteStringUtils.equals(filedName, kiteAttr.getFieldName())) {
//                kiteAttr.setValue(filedValue);
//                kiteAttr.setValueDesc(filedValue);
//            }
//        });
//        operateSceneInstService.putExtParameter(sceneInstId, "wholeQuickEntryMap", wholeQuickEntryMap);

        // 已实例化的可选包
        List<KiteOfferInst> additionalOfferInsts = new ArrayList<>();
        for (String offerInstId : offerInstIdList) {
            additionalOfferInsts.add(querySceneInstService.getOfferInst(custId, offerInstId));
        }
        return additionalOfferInsts;
    }
}
